package cn.edu.njtc.service.impl;

import cn.edu.njtc.entity.pojo.QRCodeGenerator;
import cn.edu.njtc.mapper.QRCodeGeneratorMapper;
import cn.edu.njtc.service.QRCodeGeneratorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

@Service
@Transactional
public class QRCodeGeneratorServiceImpl extends ServiceImpl<QRCodeGeneratorMapper,QRCodeGenerator> implements QRCodeGeneratorService {

    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 300;


    @Override
    public QRCodeGenerator generateQRCode(String qrCodeData, String filePath, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

        QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
        qrCodeGenerator.setQrCodeData(qrCodeData);
        qrCodeGenerator.setFilePath(filePath);
        qrCodeGenerator.setWidth(width);
        qrCodeGenerator.setHeight(height);

        return qrCodeGenerator;
    }

    // 新增：删除二维码文件实现
    @Override
    public boolean deleteQRCode(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return false;
        }

        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        return false;
    }
}